//实时监听键盘打开关闭状态
export function keyboardDetection() {
    const isKeyboardOpen = ref(false)

    const initialHeight = ref(0)

    // 监听窗口大小变化
    const handleResize = () => {
        // 如果初始高度为空，则将当前窗口高度赋值给初始高度
        if (!initialHeight.value) {
            initialHeight.value = window.innerHeight
        }

        // 获取当前窗口高度
        const currentHeight = window.innerHeight
        const threshold = 100 // 阈值，避免误判

        if (currentHeight + threshold < initialHeight.value) {
            isKeyboardOpen.value = true
        } else if (currentHeight - threshold > initialHeight.value) {
            isKeyboardOpen.value = false
            initialHeight.value = currentHeight
        }
    }

    // 处理焦点事件
    const handleFocus = () => {
        // 将键盘是否打开的值设置为true
        isKeyboardOpen.value = true
    }

    // 处理失去焦点事件
    const handleBlur = () => {
        // 将键盘是否打开的值设为false
        isKeyboardOpen.value = false
    }

    onMounted(() => {
        initialHeight.value = window.innerHeight
        window.addEventListener('resize', handleResize)
    })

    onUnmounted(() => {
        window.removeEventListener('resize', handleResize)
    })

    return {
        keyboardStatus: computed(() => isKeyboardOpen.value),
        handleFocus,
        handleBlur
    }
}